/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useEffect, useState, useRef } from 'react';
import { connect } from 'dva';
import { Modal, Form, Input, Button, Row, Col, Tooltip, message } from 'antd';
import question from '@/assets/question.svg';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
};

const tooltip =
  '该手机为您所维护的工号在梧桐系统所对应的手机号，如需要修改，请至梧桐系统-快递业务-网点信息维护-用户资料内修改';

const PhoneVerificationCode = Form.create()(props => {
  const {
    dispatch,
    childern,
    visible,
    triggleOpen,
    title,
    form,
    phone,
    isPass,
    message: warnMessage,
    submiting,
    account,
    ...restProps
  } = props;
  const { getFieldDecorator, validateFields, setFieldsValue } = form;

  const [countDown, setCountDown] = useState(60);
  const [isSuccess, setSuccess] = useState(true);
  const [phoneForShow, setPhoneForShow] = useState('');
  const timerRef = useRef('');

  useEffect(
    () => {
      phone &&
        setPhoneForShow(
          `${phone.toString().substring(0, 3)}****${phone.toString().substring(7, 11)}`,
        );
    },
    [phone],
  );

  useEffect(
    () => {
      clearInterval(timerRef.current);
      setCountDown(60);
      setSuccess(true);
    },
    [visible],
  );

  useEffect(
    () => {
      if (countDown <= 0) {
        setCountDown(60);
        clearInterval(timerRef.current);
        setSuccess(true);
      }
    },
    [countDown],
  );

  const handleOk = useCallback(
    () => {
      phone
        ? validateFields((err, values) => {
            if (err) return;
            dispatch({
              type: 'allocation/stoCheckPhone',
              payload: {
                mobile: phone,
                account,
                ...values,
              },
            })
              .then(res => {
                if (res.code === 0) {
                  triggleOpen(false, true);
                }
              })
              .catch(error => {
                message.error(error.msg);
                clearInterval(timerRef.current);
                setCountDown(10);
                setSuccess(true);
                setFieldsValue({ verify_code: '' });
              });
          })
        : triggleOpen(false);
    },
    [visible, phone],
  );

  const handleCancel = useCallback(() => {
    triggleOpen(false, false);
  }, []);

  const onCountDownClick = () => {
    dispatch({
      type: 'allocation/getShortMessage',
      payload: {
        mobile: phone,
        account,
      },
    }).then(() => {
      timerRef.current = setInterval(() => {
        // eslint-disable-next-line no-return-assign
        setCountDown(prevCount => (prevCount -= 1));
      }, 1000);
      setSuccess(false);
    });
  };

  return (
    <Modal
      confirmLoading={submiting}
      destroyOnClose
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      {...restProps}
    >
      {phone ? (
        <Form>
          <FormItem label="手机号" {...formItemLayout}>
            <Row type="flex" align="middle">
              <Col>{phoneForShow}</Col>
              <Col push={1}>
                <Tooltip placement="topLeft" arrowPointAtCenter title={tooltip}>
                  <img src={question} alt="" />
                </Tooltip>
              </Col>
            </Row>
          </FormItem>
          <FormItem label="验证码" {...formItemLayout}>
            <Row type="flex">
              <Col span={12}>
                {getFieldDecorator('verify_code', {
                  rules: [
                    {
                      required: true,
                      message: '请输入验证码',
                    },
                  ],
                })(<Input placeholder="请输入验证码" />)}
              </Col>
              <Col span={12} push={1}>
                {isSuccess ? (
                  <Button type="primary" onClick={onCountDownClick}>
                    获取验证码
                  </Button>
                ) : (
                  <Button disabled>
                    {countDown}
                    s后重发
                  </Button>
                )}
              </Col>
            </Row>
          </FormItem>
        </Form>
      ) : (
        <div>{warnMessage}</div>
      )}
    </Modal>
  );
});

export default connect(({ loading }) => ({
  submiting: loading.effects['allocation/stoCheckPhone'],
}))(PhoneVerificationCode);
